package com.gjs.management.controller;

import cn.hutool.core.bean.BeanUtil;
import com.gjs.common.exception.BizException;
import com.gjs.common.manager.response.RspBody;
import com.gjs.management.pojo.dto.permission.SysPermissionQueryDTO;
import com.gjs.management.pojo.entity.SysPermission;
import com.gjs.management.pojo.vo.permission.SysPermissionRspVO;
import com.gjs.management.service.ISysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Api(tags = "权限接口")
@RequiredArgsConstructor
@RequestMapping("/permission")
public class PermissionController {

    private final ISysPermissionService permissionService;

    @GetMapping("/get_nodes")
    @ApiOperation("权限树节点")
    public RspBody<List<SysPermissionRspVO>> getNodes(@Validated SysPermissionQueryDTO queryDTO) {
        List<SysPermissionRspVO> sysPermissionRspVOList = permissionService.list(permissionService.buildWrapper(queryDTO))
                .stream()
                .map(row -> BeanUtil.copyProperties(row, SysPermissionRspVO.class))
                .collect(Collectors.toList());
        return RspBody.success(sysPermissionRspVOList);
    }

    @PostMapping("/edit_permission_name")
    @ApiOperation("编辑权限名称")
    public RspBody<Boolean> editPermissionName(@RequestBody SysPermission permission) {
        SysPermission sysPermission = permissionService.getById(permission.getId());
        if (sysPermission == null) {
            throw new BizException("找不到该权限");
        }
        sysPermission.setPermissionName(permission.getPermissionName());
        return RspBody.success(permissionService.updateById(sysPermission));
    }

    @PostMapping("/add_sub_permission")
    @ApiOperation("添加子权限")
    public RspBody<Boolean> addSubPermission(@RequestBody SysPermission newSubPermission) {
        return RspBody.success(permissionService.save(newSubPermission));
    }
}
